﻿@namespace MudBlazor.Docs.Examples

@inject IScrollListenerFactory ScrollListenerFactory
@implements IDisposable

<MudStack>
    <MudText>You can attach the scroll listener to any element:</MudText>
    <MudStack>
        <MudText>Rectangle scroll position: @_scrollTopRectangle px</MudText>
        <div id="scroll_div" style="height: 5rem; width: 100%; overflow-y: scroll; scrollbar-width: auto; background-color: rgba(0,0,0,0.5); border-radius: var(--mud-default-borderradius);">
            <MudStack Spacing="0" Style="color: var(--mud-palette-text-primary); background-color: var(--mud-palette-background);" Class="pa-4">
                @for (var i = 0; i < 100; i++)
                {
                    var iLocal = i;
                    <MudText>Line @iLocal</MudText>
                }
            </MudStack>
        </div>
    </MudStack>
</MudStack>


@code {
    private double _scrollTopRectangle;
    private IScrollListener _scrollListenerRect;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            _scrollListenerRect = ScrollListenerFactory.Create("#scroll_div");
            _scrollListenerRect.OnScroll += ScrollListenerRectOnScroll;
        }
    }

    public void Dispose()
    {
        _scrollListenerRect?.Dispose();
    }

    private void ScrollListenerRectOnScroll(object sender, ScrollEventArgs e)
    {
        _scrollTopRectangle = e.ScrollTop;
        StateHasChanged();
    }
}
